package guiTest;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Comparator;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;

public class GUI_Creator implements ActionListener, DocumentListener
{
	// The JFrame
	JFrame myFrame;
	
	// The Panels
	JPanel myPanel;	
	JPanel titlePanel;
	JPanel logoPanel;
	JPanel statusPanel;
	JPanel songPanel;
	JPanel controlPanel;
	JPanel tablePanel;
	
	//logoPanel components
	JLabel logoLabel;
	ImageIcon musicNoteLogo;
	ImageLabel imageLabel;
	
	// titlePanel components
	JLabel playerTitle;
	
	// songPanel components
	JLabel artistLabel;
	JLabel songLabel;	
	JLabel durationLabel;
	JLabel ratingLabel;
	
	JLabel artistValueLabel;
	JLabel songValueLabel;	
	JLabel durationValueLabel;
	JLabel ratingValueLabel;
	
	JLabel timeLabel;
	
	JLabel numberOfSongsShown;
	JLabel durationOfSongsShown;
	
	JSlider mySlider;
	JTextField searchBox;
	
	//controlPanel components
	JButton pauseButton;
	JButton randomizeButton;
	JButton showInTableButton;
	
	// tablePanel components
	JTable allSongsTable;
	JScrollPane songsTableScrollPane;
	MusicTableModel myTableModel;
	
	// table sorter
	TableRowSorter<MusicTableModel> sorter;
	
	// modePanel components
	// Do this later
	
	//JTable playedSongsTable;
	
	// controlPanel components
	Thread currentThread;
	MP3_Test_Song currentSong;
	MP3_Test_Status currentStatus;
	SongData allSongData;
	
	Timer myTimer;
	
	static final int TABLE_WIDTH = 1000;
	static final int TABLE_HEIGHT = 600;
	static final int COL_WIDTHS[] = {410, 300, 180, 110}; 
	
	public static int ACTIVE_COLUMN = -1;
	public static int ACTIVE_CLICKS = 0;
	
	public GUI_Creator()
	{
		// Main JFrame Options
		JFrame.setDefaultLookAndFeelDecorated(true);
		myFrame = new JFrame("The Java Music Player");
		myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myFrame.setResizable(false);
		
		// Set up the JPanels
		myPanel = new JPanel();
		titlePanel = new JPanel();
		logoPanel = new JPanel();
		songPanel = new JPanel();
		controlPanel = new JPanel();
		tablePanel = new JPanel();
		statusPanel = new JPanel();
				
		myPanel.setLayout(new GridBagLayout());
		titlePanel.setLayout(new GridBagLayout());
		logoPanel.setLayout(new GridBagLayout());
		songPanel.setLayout(new GridBagLayout());
		controlPanel.setLayout(new GridBagLayout());
		tablePanel.setLayout(new GridBagLayout());
		statusPanel.setLayout(new GridBagLayout());
		
		myPanel.setBackground(Settings.BACKGROUND_COLOR);
		titlePanel.setBackground(Settings.BACKGROUND_COLOR);
		logoPanel.setBackground(Settings.BACKGROUND_COLOR);
		songPanel.setBackground(Settings.BACKGROUND_COLOR);
		controlPanel.setBackground(Settings.BACKGROUND_COLOR);
		tablePanel.setBackground(Settings.BACKGROUND_COLOR);
		statusPanel.setBackground(Settings.BACKGROUND_COLOR);
		
		
		// Set up the GridBagConstraints object
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.CENTER;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.ipady = 3;
		
		// Set up Fonts and Borders
		Font titleFont = new Font(Settings.FONT_NAME, Font.BOLD, 28);
		Font regularFont = new Font(Settings.FONT_NAME, Font.PLAIN, 14);
		
		Border stdFullBorder = BorderFactory.createEmptyBorder(4, 4, 4, 4);
		Border bigFullBorder = BorderFactory.createEmptyBorder(15, 15, 15, 15);
		Border tableBorder = BorderFactory.createLineBorder(Color.DARK_GRAY, 1);
		
		// Set up the titlePanel
		playerTitle = new JLabel("The Java Music Player");
		playerTitle.setForeground(Settings.FOREGROUND_COLOR);
		playerTitle.setFont(titleFont);
		playerTitle.setBorder(stdFullBorder);
		
		titlePanel.add(playerTitle, gbc);
		
		// Set up the logoPanel
		/*musicNoteLogo = new ImageIcon("C:\\Documents and Settings\\BJ\\My Documents\\" +
			"My Files\\Icons\\MusicNote3.png");
		
		logoLabel = new JLabel(musicNoteLogo);
		logoLabel.setBorder(stdFullBorder);
		
		logoPanel.setPreferredSize(new Dimension(150, 150));
		logoPanel.add(logoLabel, gbc);*/
		/*
		imageLabel = new ImageLabel("C:\\Documents and Settings\\BJ\\My Documents\\" +
			"My Files\\Icons\\MusicNote3.png");
		
		imageLabel.setBorder(stdFullBorder);
		imageLabel.setPreferredSize(new Dimension(150, 150));
		imageLabel.setMaximumSize(new Dimension(150, 150));
		imageLabel.setMinimumSize(new Dimension(150, 150));
		
		logoPanel.setPreferredSize(new Dimension(150, 150));
		logoPanel.add(imageLabel, gbc);
		*/
		
		// Set up the songPanel
		timeLabel = new JLabel("0:00");
		timeLabel.setFont(titleFont);
		timeLabel.setForeground(Settings.FOREGROUND_COLOR);
		timeLabel.setBorder(stdFullBorder);
		
		songLabel = new JLabel("Song: ");
		songLabel.setFont(regularFont);
		songLabel.setForeground(Settings.FOREGROUND_COLOR);
		songLabel.setBorder(stdFullBorder);
		
		songValueLabel = new JLabel("");
		songValueLabel.setFont(regularFont);
		songValueLabel.setForeground(Settings.FOREGROUND_COLOR);
		songValueLabel.setBorder(stdFullBorder);
		
		artistLabel = new JLabel("Artist: ");
		artistLabel.setFont(regularFont);
		artistLabel.setForeground(Settings.FOREGROUND_COLOR);
		artistLabel.setBorder(stdFullBorder);
		
		artistValueLabel = new JLabel("");
		artistValueLabel.setFont(regularFont);
		artistValueLabel.setForeground(Settings.FOREGROUND_COLOR);
		artistValueLabel.setBorder(stdFullBorder);
		
		durationLabel = new JLabel("Duration: ");
		durationLabel.setFont(regularFont);
		durationLabel.setForeground(Settings.FOREGROUND_COLOR);
		durationLabel.setBorder(stdFullBorder);
		
		durationValueLabel = new JLabel("");
		durationValueLabel.setFont(regularFont);
		durationValueLabel.setForeground(Settings.FOREGROUND_COLOR);
		durationValueLabel.setBorder(stdFullBorder);
		
		ratingLabel = new JLabel("Rating: ");
		ratingLabel.setFont(regularFont);
		ratingLabel.setForeground(Settings.FOREGROUND_COLOR);
		ratingLabel.setBorder(stdFullBorder);
		
		ratingValueLabel = new JLabel("(rating here)");
		ratingValueLabel.setFont(regularFont);
		ratingValueLabel.setForeground(Settings.FOREGROUND_COLOR);
		ratingValueLabel.setBorder(stdFullBorder);
		
		numberOfSongsShown = new JLabel("");
		numberOfSongsShown.setFont(regularFont);
		numberOfSongsShown.setForeground(Settings.FOREGROUND_COLOR);
		numberOfSongsShown.setBorder(stdFullBorder);
		
		durationOfSongsShown = new JLabel("");
		durationOfSongsShown.setFont(regularFont);
		durationOfSongsShown.setForeground(Settings.FOREGROUND_COLOR);
		durationOfSongsShown.setBorder(stdFullBorder);
		
		mySlider = new JSlider(JSlider.HORIZONTAL, 0, 1000, 0);
		mySlider.setBorder(stdFullBorder);
		//mySlider.setBackground(Settings.BACKGROUND_COLOR);
		mySlider.setValue(0);
		mySlider.setBackground(Settings.BACKGROUND_COLOR);
		//UIManager.put("Slider.altTrackColor", Color.WHITE);
		mySlider.setUI(new MySliderUI2());
		//mySlider.getUI().
		
		mySlider.addChangeListener(new ChangeListener()
		{
			@Override
			public void stateChanged(ChangeEvent arg) 
			{
				if(mySlider.getValueIsAdjusting())
				{
					//Debug.pl("1. " + currentStatus.getStatusStr());
					
					if(!currentStatus.isDuringDrag())
					{
						currentStatus.setIsDuringDrag(true);
					}
					
					if(!currentStatus.isPaused())
					{
						currentStatus.pause();
					}
					
					currentStatus.updateTime(1.0 * (mySlider.getValue() - 
						mySlider.getMinimum()) / (mySlider.getMaximum() - 
								mySlider.getMinimum())); 
				}
				else
				{
					//Debug.pl("2. " + currentStatus.getStatusStr());
					
					if(currentStatus.isPaused())
					{
						double percent = 
							1.0 * (mySlider.getValue() - mySlider.getMinimum()) / 
							     (mySlider.getMaximum() - mySlider.getMinimum());
						currentStatus.setPercent(percent);
						currentStatus.setIsDuringDrag(false);
						currentStatus.setIsAfterDrag(true);
						//System.out.println("Value = " + mySlider.getValue());
						currentStatus.resume();
						
						pauseButton.setText("Pause");
						
						
						// TODO - scroll song to indicated location
					}
				}
			}
		});
		
		searchBox = new JTextField(15);
		Dimension d = new Dimension(300, 26);
		searchBox.setPreferredSize(d);
		searchBox.setMaximumSize(d);
		searchBox.setMinimumSize(d);
		searchBox.setFont(new Font(Settings.FONT_NAME, Font.PLAIN, 18));
		searchBox.getDocument().addDocumentListener(this);
		//searchBox.setBorder(stdBottomBorder2);

		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.anchor = GridBagConstraints.LINE_START;
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.weightx = 0.1;
		gbc.fill = GridBagConstraints.BOTH;
		JPanel t1 = new JPanel();
		t1.add(songLabel);
		t1.setBackground(Settings.BACKGROUND_COLOR);
		songPanel.add(t1, gbc);
		
		gbc.gridx = 1;
		gbc.weightx = 0.6;
		JPanel t2 = new JPanel();
		t2.setBackground(Settings.BACKGROUND_COLOR);
		t2.add(songValueLabel);
		songPanel.add(t2, gbc);
		
		gbc.gridx = 2;
		gbc.weightx = 0.1;
		JPanel t3 = new JPanel();
		t3.setBackground(Settings.BACKGROUND_COLOR);
		t3.add(ratingLabel);
		songPanel.add(t3, gbc);
		
		gbc.gridx = 3;
		gbc.weightx = 0.2;
		JPanel t4 = new JPanel();
		t4.setBackground(Settings.BACKGROUND_COLOR);
		t4.add(ratingValueLabel);
		songPanel.add(t4, gbc);
		
		gbc.gridx = 0;
		gbc.gridy = 1;
		gbc.weightx = 0.1;
		JPanel t5 = new JPanel();
		t5.setBackground(Settings.BACKGROUND_COLOR);
		t5.add(artistLabel);
		songPanel.add(t5, gbc);
		
		gbc.gridx = 1;
		gbc.weightx = 0.6;
		JPanel t6 = new JPanel();
		t6.setBackground(Settings.BACKGROUND_COLOR);
		t6.add(artistValueLabel);
		songPanel.add(t6, gbc);
		
		gbc.gridx = 2;
		gbc.weightx = 0.1;
		JPanel t7 = new JPanel();
		t7.setBackground(Settings.BACKGROUND_COLOR);
		t7.add(durationLabel);
		songPanel.add(t7, gbc);
		
		gbc.gridx = 3;
		gbc.weightx = 0.2;
		JPanel t8 = new JPanel();
		t8.setBackground(Settings.BACKGROUND_COLOR);
		t8.add(durationValueLabel);
		songPanel.add(t8, gbc);
		
		gbc.gridy = 2;
		gbc.gridx = 0;
		gbc.weightx = 1.0;
		gbc.gridwidth = 4;
		gbc.anchor = GridBagConstraints.CENTER;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		songPanel.add(mySlider, gbc);
		
		gbc.fill = GridBagConstraints.NONE;
		gbc.gridy = 3;
		songPanel.add(timeLabel, gbc);
		
		Dimension songPanelDimension = new Dimension(460, 150);
		songPanel.setPreferredSize(songPanelDimension);
		songPanel.setMaximumSize(songPanelDimension);
		songPanel.setMinimumSize(songPanelDimension);
		
		// Set up the controlPanel
		pauseButton = new JButton("Pause");
		pauseButton.setFont(regularFont);
		//pauseButton.setBorder(stdBorder2);
		pauseButton.addActionListener(this);
		
		randomizeButton = new JButton("Randomize");
		randomizeButton.setFont(regularFont);
		//randomizeButton.setBorder(stdBorder2);
		randomizeButton.addActionListener(this);
		
		showInTableButton = new JButton("Show in Table");
		showInTableButton.setFont(regularFont);
		//nextButton.setBorder(stdBorder2);
		showInTableButton.addActionListener(this);
		
		gbc.insets = new Insets(2, 2, 0, 2);
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.weightx = 0;
		//gbc.insets = new Insets(15, 15, 15, 15);
		gbc.fill = GridBagConstraints.HORIZONTAL;
		controlPanel.add(pauseButton, gbc);
		
		gbc.gridy = 1;
		controlPanel.add(randomizeButton, gbc);
		
		gbc.insets = new Insets(2, 2, 2, 2);		
		gbc.gridy = 2;
		controlPanel.add(showInTableButton, gbc);
		
		Dimension controlPanelDimension = new Dimension(230, 150);
		controlPanel.setPreferredSize(controlPanelDimension);
		controlPanel.setMaximumSize(controlPanelDimension);
		controlPanel.setMinimumSize(controlPanelDimension);
		
		gbc.insets = new Insets(2, 2, 0, 2);
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.weightx = 0.0;
		statusPanel.add(numberOfSongsShown, gbc);
		
		gbc.gridy = 1;
		statusPanel.add(durationOfSongsShown, gbc);
		
		gbc.insets = new Insets(2, 2, 2, 2);
		gbc.gridy = 2;
		statusPanel.add(searchBox, gbc);
		gbc.insets = new Insets(0, 0, 0, 0);
		
		Dimension statusPanelDimension = new Dimension(230, 150);
		statusPanel.setPreferredSize(statusPanelDimension);
		statusPanel.setMinimumSize(statusPanelDimension);
		statusPanel.setMaximumSize(statusPanelDimension);
		
		// Set up song information
		allSongData = new SongData();
		currentStatus = new MP3_Test_Status(allSongData, this);
		currentSong = new MP3_Test_Song(currentStatus);
		currentThread = new Thread(currentSong);
	
		// Set up the tablePanel
		myTableModel = new MusicTableModel(allSongData);
		
		allSongsTable = new JTable(myTableModel);
		allSongsTable.setPreferredScrollableViewportSize(new Dimension(TABLE_WIDTH, 
				TABLE_HEIGHT));
		allSongsTable.setFillsViewportHeight(true);
		allSongsTable.setAutoCreateRowSorter(true);
		allSongsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		allSongsTable.setRowHeight(22);
		allSongsTable.setSelectionBackground(Color.yellow);
		
		MyAction handler = new MyAction(this);
		allSongsTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), 
				"enterAction");
		allSongsTable.getActionMap().put("enterAction", handler);
		/*
		allSongsTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0), 
		"eAction");
		allSongsTable.getActionMap().put("eAction", handler);*/
		
		allSongsTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), 
		"f2Action");
		allSongsTable.getActionMap().put("f2Action", new MyAction2(this));
		
		// Right align rating and order
		/*TableColumnModel colModelRight = allSongsTable.getColumnModel();
		TableColumn ratingsCol = colModelRight.getColumn(2);
		TableColumn orderCol = colModelRight.getColumn(3);
		
		ratingsCol.setCellRenderer(rightRenderer);
		orderCol.setCellRenderer(rightRenderer);*/
		
		allSongsTable.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent me)
			{
				if(me.getClickCount() == 2)
				{				
					int selectedRow = allSongsTable.getSelectedRow();
					int songRow = allSongsTable.convertRowIndexToModel(selectedRow);
					
					currentStatus.requestSong(songRow);
					if(currentStatus.isPaused())
					{
						pauseButton.setText("Pause");
						currentStatus.resume();
					}
				}
				else
				{
					if(allSongsTable.getSelectedColumn() == 2)
					{
						allSongsTable.editCellAt(allSongsTable.getSelectedRow(), 2);
					}
				}
			}
			
		});
		
		// Set up the row sorter
		sorter = new TableRowSorter<MusicTableModel>(myTableModel);
		
		// Comparator for Duration
		final Comparator<Duration> durationComparator =
			new Comparator<Duration>() 
			{
				public int compare(Duration d1, Duration d2) 
				{
					return d1.compareTo(d2);
				}
			};

		
		// Set comparator for duration
		sorter.setComparator(3, durationComparator);
		allSongsTable.setRowSorter(sorter);
		
		setTableColumnWidths();
		
		JTableHeader header = allSongsTable.getTableHeader();

		header.addMouseListener(new MouseAdapter()
		{
		    public void mouseClicked(MouseEvent evt) 
		    {
		        JTable table = ((JTableHeader)evt.getSource()).getTable();
		        TableColumnModel colModel = table.getColumnModel();

		        // The index of the column whose header was clicked
		        int vColIndex = colModel.getColumnIndexAtX(evt.getX());
		        int mColIndex = table.convertColumnIndexToModel(vColIndex);

		        
		        // Return if not clicked on any column header
		        if (vColIndex != -1)
		        {
		        	//System.out.println("Col clicked: " + mColIndex);
		        	if(mColIndex == ACTIVE_COLUMN)
		        	{
		        		ACTIVE_CLICKS++;
		        	}
		        	else
		        	{
		        		ACTIVE_COLUMN = mColIndex;
		        		ACTIVE_CLICKS = 0;
		        	}
		        	
		        	allSongsTable.getTableHeader().repaint();
		            
		        }
		        
		        return;
		    }
		});

		//JTextField editField = new JTextField(4);
		allSongsTable.getColumnModel().getColumn(2).setCellEditor(
				new SpinnerCellEditor());
		
		MusicTableListener myListener = new MusicTableListener(this);
		ListSelectionModel tableSelectionModel = allSongsTable.getSelectionModel();
		tableSelectionModel.addListSelectionListener(myListener);
		
		// Set up the timer
		myTimer = new Timer(50, this);
		myTimer.start();
		
		songsTableScrollPane = new JScrollPane(allSongsTable);
		songsTableScrollPane.setViewportBorder(tableBorder);
		songsTableScrollPane.setBorder(bigFullBorder);
		songsTableScrollPane.setBackground(Settings.BACKGROUND_COLOR);
		
		doRowSorting();
		
		gbc.gridx = 0;
		gbc.gridy = 0;
		tablePanel.add(songsTableScrollPane, gbc);

		// Sets up the myPanel
		gbc.gridwidth = 3;
		myPanel.add(titlePanel, gbc);
		
		gbc.gridwidth = 1;
		gbc.gridy = 1;
		//myPanel.add(logoPanel, gbc);
		
		gbc.gridx = 0;
		gbc.weightx = .25;
		myPanel.add(controlPanel, gbc);
		
		gbc.gridx = 1;
		gbc.weightx = .5;
		myPanel.add(songPanel, gbc);
		
		gbc.gridx = 2;
		gbc.weightx = .25;
		myPanel.add(statusPanel, gbc);
				
		gbc.gridx = 0;
		gbc.gridy = 2;
		gbc.gridwidth = 3;
		myPanel.add(tablePanel, gbc);
		
		// Add main panel to the JFrame
		myFrame.getContentPane().add(myPanel);		
		
		final SplashScreen splash = SplashScreen.getSplashScreen();
        if (splash == null)
        {
            System.out.println("SplashScreen.getSplashScreen() returned null");
            return;
        }
       
        Graphics2D g = splash.createGraphics();
        if (g == null) 
        {
            System.out.println("g is null");
            return;
        }
        
        Random r = new Random();
        
      
        for(int i = 0; i <= 100; i++) 
        {
            renderSplashFrame(g, i);
            splash.update();
            try 
            {
                Thread.sleep(r.nextInt(41) + 15);
            }
            catch(InterruptedException e) 
            {
            }
        }
	        
	        splash.close();
	}
	
    public void renderSplashFrame(Graphics2D g, int frame) 
    {
    	int xStart = 460;
    	int yStart = 400;
        g.setComposite(AlphaComposite.Clear);
        g.fillRect(xStart - 10, yStart - 70, 200, 100);
        g.setPaintMode();
        g.setColor(Color.YELLOW);
        g.setFont(new Font("Candara", Font.BOLD, 20));
        g.drawString("Loading: "+ frame + "%", xStart, yStart);
    }

	public void display()
	{
		myFrame.pack();
		myFrame.setVisible(true);
		currentThread.start();
	}
	
	public void setTableColumnWidths()
	{
		assert(allSongsTable.getColumnCount() == COL_WIDTHS.length);
		
		DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
		rightRenderer.setHorizontalAlignment(SwingConstants.LEFT);
		
		for(int i = 0; i < COL_WIDTHS.length; i++)
		{
			TableColumn curr = allSongsTable.getColumnModel().getColumn(i);
			curr.setPreferredWidth(COL_WIDTHS[i]);			
			curr.setMaxWidth(COL_WIDTHS[i]);
			curr.setMinWidth(COL_WIDTHS[i]);
			
			if(i != 2)
			{
				curr.setCellRenderer(new StandardRenderer());				
			}
			else
			{
				curr.setCellRenderer(new RatingsRenderer());
			}
			
			curr.setHeaderRenderer(new StandardHeaderRenderer());
			/*
			allSongsTable.getTableHeader().getColumnModel().getColumn(i
					).setCellRenderer(new StandardRenderer());*/
		}
	}
	
	public void respond(int rowNumber)
	{
		Song selectedSong = myTableModel.getSong(rowNumber);
		//artistLabel.setText("Artist: " + selectedSong.getArtist());
		//songLabel.setText("Song: " + selectedSong.getSong());
	}
	
	public void updateLabels(Song songPlaying)
	{
		artistValueLabel.setText(songPlaying.getArtist());
		songValueLabel.setText(songPlaying.getSong());
		ratingValueLabel.setText(songPlaying.getRating().toString());
		durationValueLabel.setText(songPlaying.getDuration().toString());
		
	}
	
	public void updateTimeLabel(int seconds, int totalSeconds)
	{
		int remainder = totalSeconds - seconds;
		
		timeLabel.setText("" + seconds / 60 + ":" + 
			Duration.getSecondsString(seconds % 60) + " / " + remainder / 60 + 
			":" + Duration.getSecondsString(remainder % 60));		
	}
	
	public void updateSlider(long val)
	{
		if(currentStatus != null)
		{
			double dur = currentStatus.getCurrentSongDuration();
			double val2 = 1000.0 * val;
			int toSet = (int)(val2 / dur);
			mySlider.setValue(toSet);
			
			//System.out.println(val + " / " + dur  + "  " + toSet);
		}
	}
	
	public void respond()
	{
		// This code will do something with the row that was just selescted
		int selectedRow = allSongsTable.getSelectedRow();
		int selectedColumn = allSongsTable.getSelectedColumn();
		
		if(selectedColumn == 2 && selectedRow >= 0) 
		{
			allSongsTable.editCellAt(selectedRow, selectedColumn);
			//int songID = allSongsTable.convertRowIndexToModel(selectedRow);
			//Song selectedSong = myTableModel.getSong(songID);
			//artistLabel.setText("Artist: " + selectedSong.getArtist());
			//songLabel.setText("Song: " + selectedSong.getSong());
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == myTimer)
		{
			currentStatus.addTime();
		}
		else if(e.getSource() == randomizeButton)
		{
			currentStatus.requestRandomSong();
			
			//currentStatus.setSongName(getSongFilename());
			if(currentStatus.isPaused())
			{
				currentStatus.resume();
			}			
			
			pauseButton.setText("Pause");
		}
		else if(e.getSource() == pauseButton)
		{
			if(!currentStatus.isPaused())
			{
				pauseButton.setText("Resume");
				currentStatus.pause();
			}
			else
			{
				pauseButton.setText("Pause");
				currentStatus.resume();
			}
		}
		else if(e.getSource() == showInTableButton)
		{
			int tableRow = 
				allSongsTable.convertRowIndexToView(
					currentStatus.getCurrentSongNumber());
			
			if(tableRow >= 0)
			{
				allSongsTable.setRowSelectionInterval(tableRow, tableRow);
				
				int extraRowsShown = 
					(int)(allSongsTable.getVisibleRect().getHeight() / 
							allSongsTable.getRowHeight()) - 1;
				
				int top = (tableRow - (extraRowsShown / 2)) * 
					allSongsTable.getRowHeight();
				top = Math.max(top, 0);
					
				int bottom = (tableRow + 1 + (extraRowsShown / 2)) * 
					allSongsTable.getRowHeight();
				bottom = Math.min(bottom, allSongsTable.getRowCount() * 
						allSongsTable.getRowHeight());
				
				allSongsTable.scrollRectToVisible(new Rectangle(0, top,	
						allSongsTable.getWidth(), bottom - top));
			}

		}
	}
	
	public void doRowSorting()
	{
		String text = searchBox.getText();
		
        if (text.length() == 0) 
        {
        	sorter.setRowFilter(null);
        } 
        else 
        {
        	sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
        }	
        
        int numSongs = allSongsTable.getRowCount();
        //System.out.println("RC = " + numSongs);
        numberOfSongsShown.setText("Songs Shown: " + numSongs);
        
        int totalSeconds = 0;
        
        for(int k = 0; k < numSongs; k++)
        {
        	int j = allSongsTable.convertRowIndexToModel(k);
        	totalSeconds += allSongData.getSong(j).getDuration().getDurationInSeconds();       	
        }
        
        durationOfSongsShown.setText("Total Duration: " + getDurationStr(totalSeconds));
        //System.out.println("Time = " + totalSeconds);
	}
	
	public static String getDurationStr(int s)
	{
		String tr = "";
		if(s > 3600 * 24)
		{
			int days = s / (3600 * 24);
			tr += "" + days + (days == 1 ? " day" : " days") + ", ";
		}
		
		int s2 = s % (3600 * 24);
		if(s2 != 0)
		{
			tr += "" + s2 / 3600 + ":";
		}
		
		int s3 = s2 % 3600;
		tr += "" + getMinSecStr(s3 / 60) + ":";
		
		tr += "" + getMinSecStr(s3 % 60);
		
		return tr;
	}
	
	public static String getMinSecStr(int val)
	{
		if(val < 10)
		{
			return ("0" + val);
		}
		
		return ("" + val);
	}
	
	public void changedUpdate(DocumentEvent e) 
	{
		doRowSorting();
	}
	
	public void removeUpdate(DocumentEvent e) 
	{
		doRowSorting();
	}
	
	public void insertUpdate(DocumentEvent e) 
	{
		doRowSorting();
	}

	public void selectSong() 
	{
		int selectedRow = allSongsTable.getSelectedRow();
		int songRow = allSongsTable.convertRowIndexToModel(selectedRow);
		
		currentStatus.requestSong(songRow);		
	}
	
	public void changeRating()
	{
		int r = allSongsTable.getSelectedRow();
		/*int c = 2;
		String k = allSongsTable.getValueAt(r, 2).toString();
		k.replaceAll("[a-zA-Z]", "");*/
		//allSongsTable.setValueAt(k, r, 2);
		
		allSongsTable.setColumnSelectionInterval(2, 2);
		allSongsTable.editCellAt(r, 2);
	}
	
}

/*
    /**
     * Install keyboard shortcuts.
     *
    public void setKeyBoardShortcut()
    {
        KeyStroke jKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_J, 0, false);
        KeyStroke ctrlPKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK, false);
        KeyStroke altSKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.ALT_MASK, false);
        KeyStroke vKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, 0, false);
        String searchID = "TAGSEARCH";
        String preferenceID = "PREFERENCES";
        String skinbrowserID = "SKINBROWSER";
        String stopplayerID = "STOPPLAYER";
        Action searchAction = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (mp != null) mp.processJumpToFile(e.getModifiers());
            }
        };
        Action preferencesAction = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (mp != null) mp.processPreferences(e.getModifiers());
            }
        };
        Action skinbrowserAction = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (mp != null) mp.processSkinBrowser(e.getModifiers());
            }
        };
        Action stopplayerAction = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (mp != null) mp.processStop(MouseEvent.BUTTON1_MASK);
            }
        };
        setKeyboardAction(searchID, jKeyStroke, searchAction);
        setKeyboardAction(preferenceID, ctrlPKeyStroke, preferencesAction);
        setKeyboardAction(skinbrowserID, altSKeyStroke, skinbrowserAction);
        setKeyboardAction(stopplayerID, vKeyStroke, stopplayerAction);
    }

    **
     * Set keyboard key shortcut for the whole player.
     * @param id
     * @param key
     * @param action
     *
    public void setKeyboardAction(String id, KeyStroke key, Action action)
    {
        mp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, id);
        mp.getActionMap().put(id, action);
        mp.getPlaylistUI().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, id);
        mp.getPlaylistUI().getActionMap().put(id, action);
        mp.getEqualizerUI().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, id);
        mp.getEqualizerUI().getActionMap().put(id, action);
    }
 */
